<?php
/**
 * 数据库操作
 * 
 * @package Lib
 * @author 光哥  <439884988@qq.com>
 * @license  http://www.easymvc.com 
 * @version 1.0.0
 * @package	Lib
 */


if(!defined('EASYMVC')) {
	exit('Access Denied');
}
/**
 * db 
 */
class Lib_Db {
	
	/**
	 * 数据库配置文件
	 * @access protected
	 * @var string
	 */
	
	static protected $db_config_file = 'db_config';
	
	/**
	 * 数据库资源数组
	 * @access protected
	 * @var array
	 */
	
	static protected $dbs = array();
	
	/**
	 * 数据库连接函数
	 * @param string $config_name
	 * @param string $type 0 read 1 write
	 * @param int    $pconnect
	 * @param string $class  PdoMysql|mysql
	 * @return resource  $db
	 */
	
	public static function connectDb($config_name,$type=0,$pconnect=0,$class="Mysql"){
		$key = $config_name.'_'.$type.'_'.$class.'_'.$pconnect;
		if(!isset(self::$dbs[$key])){
			$config = Frame_Config::get(self::$db_config_file);
			
			if(!$config){
				throw new Exception('db config file no exists');
			}
			$server = $config[$class][$config_name][$type];
			$class = "Lib_Db_{$class}";
			$db = new $class();
				
			 //随机选择一台 mysql 服务器
			$host_array = explode(',',$server['host']);
			$rand_keys= array_rand($host_array,1);
			$host = $host_array[$rand_keys];
			
			// 连接 mysql 服务器
			
			$db->connect($host,$server['port'],$server['name'],$server['user'],$server['pass'],$pconnect);
			
			self::$dbs[] = $db;
		}else{
			$db = self::$dbs[$key];
		}
		
		return $db;
	}
}


?>